const { app, BrowserWindow, ipcMain, dialog, Menu, MenuItem, nativeTheme, Tray, nativeImage } = require('electron');
const path = require('path')
const fs = require('fs')
//创建文件
fs.writeFileSync(path.join(__dirname, 'drag_drop_file1.txt'), 'First file to test drag and drop file', () => {
  app.addRecentDocument(path.join(__dirname, 'drag_drop_file1.txt'))
})
fs.writeFileSync(path.join(__dirname, 'drag_drop_file2.txt'), 'Second file to test drag and drop file', () => {
  app.addRecentDocument(path.join(__dirname, 'drag_drop_file2.txt'))
}) 

//设置应用程序标题
const handleSetTitle = (event, title) => {
  const webContents = event.sender
  const win = BrowserWindow.fromWebContents(webContents)
  win.setTitle(title)

} 
//暗黑模式切换
const handleDarkModeToggle = () => {
  if (nativeTheme.shouldUseDarkColors) {
    nativeTheme.themeSource = 'light'
  } else {
    nativeTheme.themeSource = 'dark'
  }
  return nativeTheme.shouldUseDarkColors
}
const handleFileOpen = async event => {
  const webContents = event.sender
  const win = BrowserWindow.fromWebContents(webContents)
  const { canceled, filePaths } = await dialog.showOpenDialog(win, {
    properties: ['openDirectory']
  })
  if (canceled) return;
  return filePaths[0]
}

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    titleBarStyle: 'hidden',
    // trafficLightPosition: {
    //   x: 10, y: 10
    // },
    transparent: false, 
    titleBarOverlay: {
      color: 'rgba(0,0,0,0)',
      //按钮颜色
      symbolColor: '#fff'
    }, 
    // titleBarOverlay: true, 
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    }
  }); 

  // const menu = new Menu()
  // menu.append(new MenuItem({
  //   label: '菜单一',
  //   submenu: [
  //     {
  //       label: 'Increment', 
  //       click: () => win.webContents.send('update-counter', 1)
  //     },
  //     {
  //       label: 'Decrement', 
  //       click: () => win.webContents.send('update-counter', -1)
  //     },
  //     {
  //       label: '切换开发者模式',  
  //       click: () => win.webContents.toggleDevTools()
  //     },{
  //       label: '打开最近文件',
  //       role: 'recentDocuments',
  //       submenu: [
  //         {
  //           label: '清空最近',
  //           role: 'clearRecentDocuments'
  //         }
  //       ]
  //     }
  //   ] 
  // })) 
  // Menu.setApplicationMenu(menu) 



  // win.setThumbarButtons([
  //   {
  //     tooltip: 'button1',
  //     icon: path.join(__dirname, 'static/logo.png'),
  //     click () { console.log('button1 clicked') }
  //   }, {
  //     tooltip: 'button2',
  //     icon: path.join(__dirname, 'static/logo.png'),
  //     flags: ['enabled', 'dismissonclick'],
  //     click () { console.log('button2 clicked.') }
  //   }
  // ])

  // win.setOverlayIcon(path.join(__dirname, 'static/logo.png'), 'Description for overlay')

  // win.once('focus', () => win.flashFrame(false)) 
  // win.flashFrame(true) 

  win.webContents.openDevTools()

  if(process.env.npm_lifecycle_event && process.env.npm_lifecycle_event.indexOf('dev') > -1) {
    win.loadURL('http://localhost:8611')
  } else {
    win.loadFile('./dist/index.html')
  }
};
//更新进度条
const updateProcessBar = (event, num) => {
  const webContents = event.sender
  const currWin = BrowserWindow.fromWebContents(webContents)
  if (num == 1) {
    currWin.setProgressBar(-1, {mode: 'normal'})
  } else {
    currWin.setProgressBar(num, {mode: 'normal'})
  } 
}
// 管理最近文档
const recentlyFile = 'recently-used.md'
fs.writeFile(recentlyFile, 'Recently used file', () => {
  console.log('====addRecentDocument====')
  app.addRecentDocument(path.join(__dirname, recentlyFile))
})

app.whenReady().then(() => {
  createWindow();
  // 创建托盘图标
  const trayIcon = nativeImage.createFromPath(path.join(__dirname, 'static/logo.png'))
  let tray = new Tray(trayIcon)

  const contextMenu = Menu.buildFromTemplate([
    {label: 'Item1', type: 'normal'},
    {label: 'Item2', type: 'normal'},
    {label: 'Item3', type: 'normal'},
    {label: 'Item4', type: 'normal'},
    {label: 'Item5', type: 'normal'}
  ])
 
  tray.setContextMenu(contextMenu)


  tray.setToolTip('This is my application')
  tray.setTitle('This is my title')

  app.setUserTasks([{
    program: process.execPath,
    arguments: '--new-window',
    iconPath: process.execPath,
    iconIndex: 0,
    title: 'new Window',
    description: 'create a new Window'
  }])

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  }); 

  ipcMain.handle('ping', () => 'pong') 
  ipcMain.on('set-title', handleSetTitle)
  ipcMain.handle('dialog:openFile', handleFileOpen)
  ipcMain.on('counter-value', (event, value) => {
    console.log(value)
  })
  ipcMain.on('port', event => {
    const port = event.ports[0]
    port.on('message', event => {
      const {data} = event
      console.log(data)
    })
    port.start()
  })
  ipcMain.handle('dark-mode:toggle', handleDarkModeToggle)
  ipcMain.handle('dark-mode:system', () => {
    nativeTheme.themeSource = 'system'
  })

  ipcMain.on('file:dragstart', (event, filepath) => {
    console.log(path.join(__dirname, filepath))
    event.sender.startDrag({
      file: path.join(__dirname, filepath),
      icon: path.join(__dirname, '/static/logo.png')
    })
  })

  ipcMain.on('processBar:update', updateProcessBar)

});

app.on('window-all-closed', () => {
  app.clearRecentDocuments()
  if (process.platform !== 'darwin') app.quit();
});